package com.appistry.management.domain.impl;

import java.net.InetAddress;
import java.util.Map;

import org.json.JSONException;

import com.appistry.api.rest.domain.RestResponse;
import com.appistry.management.FabricArchive;
import com.appistry.management.FabricArchiveInfo;
import com.appistry.management.State;
import com.appistry.management.domain.AbstractRestDomainObject;
import com.appistry.management.exception.FabricManagerException;
import com.appistry.management.rest.RestFabricManager;
import com.appistry.management.util.JsonTransformUtil;

public class FabricArchiveImpl extends AbstractRestDomainObject implements FabricArchive{
	private RestFabricManager restFabricManager;
	private String name;

	public FabricArchiveImpl(RestFabricManager restFabricManager, String name) {
		this.restFabricManager = restFabricManager;
		this.name = name;
	}

	public FabricArchiveInfo getFabricArchiveInfo(boolean showDeleted) throws FabricManagerException {
		try {
			RestResponse restResponse = restFabricManager.getFabricArchiveInfo(name, showDeleted);
			checkForErrors(restResponse);
			
			FabricArchiveInfo farInfo = JsonTransformUtil.toFabricArchiveInfo(restResponse.getBodyAsString());
			
			return farInfo;
		} catch (JSONException e) {
			throw new FabricManagerException(PARSE_JSON_ERR, e);
		} catch (Exception e) {
			throw new FabricManagerException(e);
		}
	}

	public String getName() {
		return name;
	}

	public Map<InetAddress, State> getState() throws FabricManagerException {
		try {
			RestResponse restResponse = restFabricManager.getFabricArchiveState(name, true);
			checkForErrors(restResponse);
			
			Map<InetAddress, State> workerStateMap = JsonTransformUtil.toWorkerStateMap(restResponse.getBodyAsString());
			
			return workerStateMap;
		} catch (JSONException e) {
			throw new FabricManagerException(PARSE_JSON_ERR, e);
		} catch (Exception e) {
			throw new FabricManagerException(e);
		}
	}
	
	
}
